/*
 * @Description: 可编辑表格
 * @Date: 2023-06-02 09:44:43
 * @Author: jiao-xiao-lin
 */
import React, { memo, useMemo, useState } from 'react';
import { Table, Button, Form, Typography, Popconfirm, message } from 'antd';
import { unstable_batchedUpdates as batchUpdateState } from 'react-dom';

import { createExcelFile } from '@/utils/fileFunc';
import { cloneDeep, forEach, findIndex } from 'lodash';
import PropTypes from 'prop-types';
import styles from './index.less';
import EditableCell from './EditableCell';
import {
  addBaseLineDetail,
  deleteBaseLineDetail,
} from '@/api/game_managememnt';

export const EditTable = (props) => {
  const {
    // 列表展示的数据
    dataSource = [],
    // 表头的数据
    columns = [],
    // 表格行 key 的取值
    rowKey = 'key',
    // rowClassNameConfig背景色配置项: 1.修改背景色key的取值 2.rowClassName:行类名
    rowClassNameConfig = {},
    // excel文件展示的列配置项
    excelColumns = [],
    // 选择类型 checkbox | radio 空为不可选择
    selectMode = '',
    // 是否显示新增按钮
    ifAddBtn = true,
    // 是否显示导出按钮
    ifExportBtn = false,
    // fontsizeStyleConfig 字体样式配置:1.baseKey 字段标识 2.baseValue基准值 3.defaultClassName默认类名 4.specialClassName 特殊类名
    fontsizeStyleConfig = {},
    setList = null,
  } = props;
  const [form] = Form.useForm();
  const [editingKey, setEditingKey] = useState(''); // 是否可编辑的key标识
  const [selectedRowKeys, setSelectedRowKeys] = useState(''); // checkbox已选项key集合
  const [selectData, setSelectData] = useState([]); // 已选的行数据
  const [ifAdd, setIfAdd] = useState(false); // 是否新增状态
  const isEditing = (record) => {
    return record.id === editingKey;
  };

  // 添加
  const handleAdd = () => {
    setIfAdd(true);
    let newData = cloneDeep(dataSource);
    // debugger
    // const id = (Math.random() + new Date().getTime()).toString(32).slice(0, 8);
    const id = dataSource.length + 1;
    // 如果当前处于新增状态，不能继续新增
    if (editingKey !== '' && newData.length) {
      message.error('请先保存');
      return;
    }
    const arr = Object.keys(dataSource);
    let data = {};
    // 生成一行表格对象
    forEach(arr, (item) => {
      data[item] = '';
    });
    const row = {
      ...data,
      id,
    };
    newData.push(row);
    batchUpdateState(() => {
      setList(newData);
      setEditingKey(id);
    });
    // 表单重置
    form.setFieldsValue(row);
  };

  // 编辑行
  const edit = (record) => {
    form.setFieldsValue(record);
    batchUpdateState(() => {
      setEditingKey(record.id);
      setIfAdd(false);
    });
  };

  // 获取行的样式类型
  const getRowClassName = (record) => {
    let className = '';
    if (record?.[rowClassNameConfig?.key] > rowClassNameConfig?.baseValue) {
      className = rowClassNameConfig?.rowClassName;
    }
    return className;
  };

  // 删除行
  const deleteRow = async (dataSource, index, record) => {
    const resp = await deleteBaseLineDetail({
      customId: record.customId,
      projectId: '614',
      gameName: record.gameName,
      fullFrame: record.fullFrame,
      // catonQuotaRule: record.catonQuotaRule,
      // name: "",
      // updateUserId: "",
      // updateUser: ""
    });
    dataSource.splice(index, 1);
    const arr = cloneDeep(dataSource);
    setList(arr);
  };

  // 取消创建、编辑
  const cancel = (dataSource, index) => {
    if (ifAdd) {
      deleteRow(dataSource, index);
    }
    setEditingKey('');
  };

  // 保存
  const save = async (id) => {
    try {
      let row = await form.validateFields();
      const newData = cloneDeep(dataSource);
      const index = findIndex(newData, (item) => id === item.id);
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, {
          ...item,
          ...row,
        });
        if (ifAdd) {
          // 如果是新增，调add接口
          const pars = {
            customId: props.customValue,
            fullFrame: Number(newData[index].fullFrame),
            projectId: '614',
            gameName: newData[index].gameName,
            // updateUserId: "詹姆斯",
            // updateUser: "詹姆斯",
            frameQuota: newData[index].frameQuota,
            jitterQuota: newData[index].jitterQuota,
            catonQuota: newData[index].catonQuota,
            worstDropFpsQuota: newData[index].worstDropFpsQuota,
            resolutionQuota: newData[index].resolutionQuota,
            id: newData[index].id,
          };
          const addResp = await addBaseLineDetail(pars);
        } else {
          // 如果是修改，调edit接口
        }
      } else {
        newData.push(row);
      }
      batchUpdateState(() => {
        setList(newData);
        setEditingKey('');
      });
    } catch (errInfo) {}
  };

  // 取消选中项
  const cancelRowSelection = () => {
    setSelectedRowKeys([]);
  };

  // 复选框配置项
  const listRowSelection = {
    type: selectMode,
    onChange: (selectedRowKeys, selectedRows) => {
      batchUpdateState(() => {
        setSelectedRowKeys(selectedRowKeys);
        setSelectData(selectedRows);
      });
    },
    selectedRowKeys,
  };

  // 导出行数据
  const exportExcel = (list) => {
    if (!list?.length) {
      message.info('请先勾选！');
      return false;
    }
    createExcelFile({ list, columns: excelColumns });
    message.success('导出成功！');
    cancelRowSelection();
  };

  const tableColumns = useMemo(() => {
    const { baseKey, baseValue, defaultClassName, specialClassName } =
      fontsizeStyleConfig;
    return columns.map((item, index) => {
      const { key, editable, dataIndex, type, title } = item;
      if (key === 'i') {
        return {
          ...item,
          render: (text, record, index) => {
            return index + 1;
          },
        };
      }
      if (key === baseKey) {
        return {
          ...item,
          render: (text, record, index) => {
            return (
              <span
                className={
                  text > baseValue ? specialClassName : defaultClassName
                }
              >
                {text || '--'}
              </span>
            );
          },
          // 可编辑单元格配置项
          onCell: editable
            ? (record, index) => ({
                record,
                type,
                inputType: 'text',
                dataIndex,
                title,
                editing: isEditing(record),
              })
            : null,
        };
      }
      if (key === 'operate') {
        return {
          ...item,
          render: (text, record, index) => {
            const editable = isEditing(record);

            return (
              <div className={styles.operate}>
                <div className={styles.left}>
                  {!editable ? (
                    <Button
                      type="link"
                      disabled={editingKey !== ''}
                      onClick={() => edit(record)}
                    >
                      编辑
                    </Button>
                  ) : (
                    <span>
                      <Typography.Link
                        onClick={() => save(record.id)}
                        style={{
                          marginRight: 8,
                        }}
                      >
                        保存
                      </Typography.Link>
                      <Popconfirm
                        title={ifAdd ? `确认取消创建？` : '确认取消编辑?'}
                        onConfirm={() => cancel(dataSource, index)}
                      >
                        <a>取消</a>
                      </Popconfirm>
                    </span>
                  )}
                </div>
                {!editable && (
                  <div className={styles.right}>
                    <Button
                      type="link"
                      disabled={editingKey !== ''}
                      onClick={() => deleteRow(dataSource, index, record)}
                    >
                      删除
                    </Button>
                  </div>
                )}
              </div>
            );
          },
        };
      }
      return {
        ...item,
        render: (text) => {
          return <div>{text || '--'}</div>;
        },
        // 可编辑单元格配置项
        onCell: editable
          ? (record, index) => ({
              record,
              inputType: 'text',
              dataIndex,
              title,
              type,
              editing: isEditing(record),
            })
          : null,
      };
    });
  }, [columns, dataSource, editingKey]);

  const tabProps = {
    components: {
      body: {
        cell: EditableCell,
      },
    },
    dataSource,
    columns: tableColumns,
    rowKey,
    rowClassName: getRowClassName,
    rowSelection: selectMode ? listRowSelection : null,
  };

  return (
    <div className={styles.commonTab}>
      {(ifAddBtn || ifExportBtn) && (
        <div className={styles.buttonArea}>
          {ifAddBtn && (
            <Button type="default" onClick={handleAdd} className={styles.add}>
              添加
            </Button>
          )}
          {ifExportBtn && (
            <Button
              type="default"
              onClick={() => {
                exportExcel(selectData);
              }}
            >
              导出
            </Button>
          )}
        </div>
      )}
      <div>
        <Form form={form} component={false}>
          <Table {...tabProps} />
        </Form>
      </div>
    </div>
  );
};
EditTable.propTypes = {
  dataSource: PropTypes.array,
  columns: PropTypes.array,
  rowKey: PropTypes.string,
  rowClassNameConfig: PropTypes.object,
  setList: PropTypes.func,
  fontsizeStyleConfig: PropTypes.object,
  excelColumns: PropTypes.array,
  selectMode: PropTypes.bool,
  ifAddBtn: PropTypes.bool,
  ifExportBtn: PropTypes.bool,
};

export default memo(EditTable);
